<?php
class Tag extends TaggingAppModel {
    public $name = 'Tag';
    public $displayField = 'name';
    public $hasMany = array(
        'Tagged' => array(
            'className' => 'Tagging.Tagged',
            'dependent' => true
        )
    );
    public $actsAs = array(
        'Tagging.Sluggable' => array(
            'label' => 'name',
            'length' => 160,
            'translation' => 'utf-8',
            'overwrite' => 1
        )
    );

    public $validate = array(
        'name' => array('notempty'),
        'slug' => array('notempty')
    );

    /* Find tags that matche the certain content */
    public function auto($content = '') {
        $matches = array();
        $content = strip_tags($content);
        if(!empty($content)){
            $tags = $this->find('list');
            foreach($tags as $tag){
                if(stripos($content, strtolower($tag)) !== false){
                    array_push($matches, $tag);
                }
            }
        }
        return $matches;
    }

    /**
     * Save a tag and the association with the tagged model
     *
     * @param string $tag Tag name
     * @param array $tagged Tagged model parameters array : tagged model name and tagged model primary key
     */
    public function saveTag($tag = '', $tagged = array()){
        if(empty($tag) or empty($tagged)){
            return;
        }

        // Tag exists ?
        $this->recursive = -1;
        if(!$this->data = $this->find(array('name' => $tag))){
            $this->data = array('Tag' => array('name' => $tag));
        }

        // Related model
        $this->data['Tagged'] = array($tagged);

        return $this->saveAll($this->data);
    }

    /**
     * Find used tags, all models
     *
     * @param array $options Options (same as classic find options)
     * Two new keys available :
     * - min_count : minimum number of times a tag is used
     * - max_count : maximum number of times a tag is used
     * @return array
     */
    public function tagCloud($options = array()){
        // Counting bounds:
        // 'min_count' and/or 'max_count' in $options ?
        $conditions = array();

        if(isset($options['min_count'])){
            $conditions[] = 'Tag.count >= ' . $options['min_count'];
            unset($options['min_count']);
        } else {
            $conditions[] = 'Tag.count > 0';
        }

        if(isset($options['max_count'])){
            $conditions[] = 'Tag.count <= ' . $options['max_count'];
            unset($options['max_count']);
        }

        $options = Set::merge(compact('conditions'), $options);

        // ORDER BY default
        if(empty($options['order'])){
            $options['order'] = 'name ASC';
        }

        // Recursive level imposed
        $options['recursive'] = -1;

        return $this->find('all', $options);
    }
}
?>